<?php
Yii::import('ext.yii-easyui.base.EuiController');
class PurchaseOrderHeaderController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			/*array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),*/
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','index','view','delete','viewPDF', 'close','getdata','quo','viewPurchaseOrderHeader'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin',),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}


	/*
		tambahan easyui
	*/
	/*public function actionGetdata(){
		header('Content-type:text/javascript;charset=UTF-8');
		$rs = QuotationOrderHeader::model()->findAll();
		$items = array();
		foreach($rs as $row)
		{
			array_push($items, $row->getAttributes(array('quotation_no','customer', 'project','attention')));
		}
		echo json_encode($items);
	}*/

	public function actionClose($id){
		PurchaseOrderHeader::model()->updateByPk($id,array('generate'=>1));
		//$this->actionViewPurchaseOrderHeader($id);
		$this->redirect(array('viewPurchaseOrderHeader','id'=>$id));
	}

	public function actionViewPurchaseOrderHeader($id){
		$modelHeader=PurchaseOrderHeader::model()->findAll('purchase_no=:purchase_no',array('purchase_no'=>$id));
		foreach ($modelHeader as $value) {
			$valueQuo=$value->quotation_no;
			$vendorId=$value->vendor_id;
		}
		$modelDetail=QuotationOrderDetail::model()->with('products','products.vendorID')
												  ->findAll('t.product_pn=products.product_pn and 
															 products.vendor_id=vendorID.id and
															 products.vendor_id=:vendor_id and 
															 quotation_no=:quotation_no',
															 array(
															 	'quotation_no'=>$valueQuo,
															 	'vendor_id'=>$vendorId,
															));

		$tempCurr=$modelHeader[0]['currency'];
		foreach ($modelDetail as $value) {
			$value->products->unit_sell=number_format($value->products->unit_sell*FormatingNumber::currency($tempCurr),2,'.',',');
		}
		

		Yii::app()->session['pk']=$id;
		$this->render('viewPurchaseOrderHeader',array(
			'modelHeader'=>$modelHeader,'modelDetail'=>$modelDetail,
		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	public function actionViewPDF($id){
		# mPDF
        $mPDF1 = Yii::app()->ePdf->mpdf();
		$model1 = PurchaseOrderHeader::model()->findByPk($id);
		$modelDetail=QuotationOrderDetail::model()->with('products','products.vendorID')
												  ->findAll('t.product_pn=products.product_pn and 
															 products.vendor_id=vendorID.id and
															 products.vendor_id=:vendor_id and 
															 quotation_no=:quotation_no',
															 array(
															 	'quotation_no'=>$model1->quotation_no,
															 	'vendor_id'=>$model1->vendor_id,
															));
		
		$this->render('viewPDF',array('modelHeader'=>$model1,'modelDetail'=>$modelDetail));

	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionQuo(){
		$params = array();
		
		if(isset($_REQUEST['rows']) && isset($_REQUEST['page'])) 
		{
			$limit = $_REQUEST['rows'];
			$params = array('limit'=>$limit, 'offset'=>($_REQUEST['page']-1) * $limit);			
		}		

		if (isset($_REQUEST['sort'])) 
		{
			$sort = $_REQUEST['sort'];
			$direction = (isset($_REQUEST['order'])) ? $_REQUEST['order'] : "";
			$params['order'] = QuotationOrderHeader::model()->getTableAlias(true).".". $sort." ".$direction;	
		}
						
		echo  $this->exportData(QuotationOrderHeader::model()->findAll($params), QuotationOrderHeader::model()->count());


		/*$model=QuotationOrderHeader::model()->findAll();
		$result = array();
	    $result["total"] = QuotationOrderHeader::model()->count();
	    $rows = array();
	    foreach ($model as $row) {
	        array_push($rows, $row->getAttributes(array(
	            'quotation_no',
	            'customer',
	            'project',
	            )));
	    }
	    $result["rows"] = $rows;
	    echo CJSON::encode($result);*/
	}

	public function actionCreate($quo_no)
	{
		$model=new PurchaseOrderHeader;
		$model->datePO=date("Y-m-d");
		$vendorList=Vendor::model()->with('products','products.quotationDetail')
								   ->findAll('id=vendor_id and 
								   			  products.product_pn=quotationDetail.product_pn and
								   			  quotation_no=:quotation_no',
								   					array('quotation_no'=>$quo_no)
								     );
		$vendorName=array();
		foreach ($vendorList as $list) {
			array_push($vendorName, $list->getAttributes('vendor'));
		}
		$currentIndex=Yii::app()->session['vendorList'];
		Yii::app()->session['sizeVendorList']=sizeof($vendorName);

		if(isset($_POST['PurchaseOrderHeader']))
		{
			$model->attributes=$_POST['PurchaseOrderHeader'];
			if($model->save()){
				if(empty($quo_no)){
					$this->redirect(array('view','id'=>$model->purchase_no));
				}else{	
					$currentIndex++;
					Yii::app()->session['vendorList']=$currentIndex;
					if($currentIndex==sizeof($vendorName) || sizeof($vendorName)==0){
						unset(Yii::app()->session['sizeVendorList']);
						unset(Yii::app()->session['vendorList']);
						if($currentIndex==sizeof($vendorName))
							$this->redirect(array('index'));
						else
							$this->redirect(array('view','id'=>$model->purchase_no));
					}
					$model=new PurchaseOrderHeader;
				}
			}
		}
		$purNo=$this->getPurNo();

		$vendorLabel=isset($vendorName[$currentIndex]['vendor'])?$vendorName[$currentIndex]['vendor']:null;
    	$vendorId=isset($vendorName[$currentIndex]['id'])?$vendorName[$currentIndex]['id']:null;

		$this->render('create',array(
			'model'=>$model,'quo_no'=>$quo_no,'purNo'=>$purNo,'vendorLabel'=>$vendorLabel,'vendorId'=>$vendorId
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$purNo=$model->purchase_no;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['PurchaseOrderHeader']))
		{
			$model->attributes=$_POST['PurchaseOrderHeader'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->purchase_no));
		}
		$vendorLabel=Vendor::model()->find('id=:vendor',array('vendor'=>$model->vendor_id));
		
		$this->render('update',array(
			'model'=>$model,'purNo'=>$purNo,'vendorLabel'=>$vendorLabel->vendor
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		//$this->loadModel($id)->delete();// sama seperti quotation
		
		PurchaseOrderHeader::model()->updateByPk($id,array('status_delete'=>'DELETED'));

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		/*if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));*/
			
		$this->redirect(array('index'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		Yii::app()->session['controller']='purchase';

		if(isset(Yii::app()->session['adminUser']))
			$model=PurchaseOrderHeader::model()->findAll('status_delete=:delete',array('delete'=>'-'));
		else
			$model=PurchaseOrderHeader::model()->with('quo_no','quo_no.po_header')->findAll('employee_id=:employee_id and t.status_delete=:delete',array('employee_id'=>$employee_id,'delete'=>'-'));

		 $this->render('admin',array(
			'model'=>$model,
		 )); 
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		/*$model=new PurchaseOrderHeader('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['PurchaseOrderHeader']))
			$model->attributes=$_GET['PurchaseOrderHeader'];

		$this->render('admin',array(
			'model'=>$model,
		));*/
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return PurchaseOrderHeader the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=PurchaseOrderHeader::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param PurchaseOrderHeader $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='purchase-order-header-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	public function getPurNo(){
            $tempCountPurchase=count(PurchaseOrderHeader::model()->findAll());
		
		$iromawi = array("","I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII");
		$temp_no='';
		if(($tempCountPurchase+1)<10)
			$temp_no='000'.($tempCountPurchase+1);
		else if(($tempCountPurchase+1)<100)
			$temp_no='00'.($tempCountPurchase+1);
		else if(($tempCountPurchase+1)<1000)
			$temp_no='0'.($tempCountPurchase+1);
		else if(($tempCountPurchase+1)>=1000)
			$temp_no=($tempCountPurchase+1);
			
                //$customer=strtoupper($customer[0]);
		
		$quo_no='PO/'.($temp_no).'/'.$iromawi[(date("m")*1)].'/'.date("Y");
		return $quo_no;
        }
}
